package edu.luas.digitalmedia.dao;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.*;

/**
 * JDBC工具类
 */
public class DBHelper {
    private static final  String DRIVERNAME = "com.mysql.cj.jdbc.Driver";
    private static final  String URL = "jdbc:mysql://47.109.42.76:3306/miaolegemiao?characterEncoding=utf-8&serverTimezone=GMT%2B8";
    private static final  String USER = "kaifamiao";
    private static final  String PASSWORD = "Kaifamiao@123";
    private static BasicDataSource dataSource = new BasicDataSource();

    /**
     * 加载数据库驱动
     */
    static {
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            System.out.println("数据库驱动注册失败！");
        }
    }
    /**
     * 设置连接池参数
     */
    static {
        dataSource.setDriverClassName(DRIVERNAME);
        dataSource.setUrl(URL);
        dataSource.setUsername(USER);
        dataSource.setPassword(PASSWORD);
    }

    /**
     * 获取连接对象
     * @return Connection
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    /**
     * 占位符赋值
     * @param statement
     * @param values
     * @throws SQLException
     */
    public static void setParameters(PreparedStatement statement, String... values)throws SQLException {
        if(values!=null && values.length>0) {
            for (int i = 0; i < values.length; i++) {
                statement.setObject(i+1, values[i]);
            }
        }
    }
    /**
     * 关闭数据库
     * @param statement
     * @param connection
     */
    public static void close(PreparedStatement statement, Connection connection) {
        close(null,statement,connection);
    }

    /**
     * 关闭数据库
     * @param rs
     * @param statement
     * @param connection
     */
    public static void close(ResultSet rs, Statement statement, Connection connection){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            rs = null;
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            statement = null;
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            connection = null;
        }
    }
}
